import { createSlice, type PayloadAction } from '@reduxjs/toolkit'

interface ArchiveData {
  id?: string
  name: string
  namecode: string
  birthDate: string
  set: string
  temphone: string
  relationship?: string
  createTime?: string
}

interface GlobalState {
	currentCity: string
	archiveData: ArchiveData | null
	archivesList: ArchiveData[]
	selectedArchiveId: string | null
}

const initialState: GlobalState = {
	currentCity: '广州',
	archiveData: null,
	archivesList: [],
	selectedArchiveId: null,
}

export const UseStateList = createSlice({
	name: 'UseStateList',
	initialState,
	reducers: {
		setCurrentCity(state, action: PayloadAction<string>) {
			state.currentCity = action.payload
		},
		setArchiveData(state, action: PayloadAction<ArchiveData>) {
			state.archiveData = action.payload
		},
		clearArchiveData(state) {
			state.archiveData = null
		},
		addArchiveToList(state, action: PayloadAction<ArchiveData>) {
			const newArchive = {
				...action.payload,
				id: `archive_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
			}
			state.archivesList.push(newArchive)
		},
		selectArchive(state, action: PayloadAction<string>) {
			state.selectedArchiveId = action.payload
			const selectedArchive = state.archivesList.find(archive => archive.id === action.payload)
			if (selectedArchive) {
				state.archiveData = selectedArchive
			}
		},
		removeArchiveFromList(state, action: PayloadAction<string>) {
			state.archivesList = state.archivesList.filter(archive => archive.id !== action.payload)
			if (state.selectedArchiveId === action.payload) {
				state.selectedArchiveId = null
				state.archiveData = null
			}
		},
	},
})
export const { 
	setCurrentCity, 
	setArchiveData, 
	clearArchiveData, 
	addArchiveToList, 
	selectArchive, 
	removeArchiveFromList 
} = UseStateList.actions

export default UseStateList.reducer